/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistense;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import model.Pessoa;

/**
 *
 * @author Cristian
 */
public class PessoaDAO {
    private static PessoaDAO instance = new PessoaDAO();
    private PessoaDAO(){
    }
    public static PessoaDAO getInstace(){
     return instance;
    }
    
    
    public void save(Pessoa pessoa) throws SQLException, ClassNotFoundException{
        Connection conn = null;
        PreparedStatement pst = null;

        try {
              conn = DataBaseLocator.getInsLocator().getConnection();
              pst = conn.prepareStatement("insert into pessoa (nome, endereco, telefone, email, cpf, rg) values(?,?,?,?,?,?)");
              pst.setString(1, pessoa.getNome());
              pst.setString(2, pessoa.getEndereco());
              pst.setString(3, pessoa.getTelefone());
              pst.setString(4, pessoa.getEmail());
              pst.setString(5, pessoa.getCpf());
              pst.setString(6, pessoa.getRg());
              pst.executeUpdate();
        } catch(SQLException e) {
                throw e;
            } finally {
                closeResources(conn, pst);
            }
        
    }
    
    public void closeResources(Connection conn, Statement st){
      try {
            if(st!=null) st.close();
            if(conn!=null) conn.close();
          } catch(SQLException e) {
                    
          }
    }

    public Pessoa buscaPessoaPorNome(String nome) {
       Connection conn = null;
       Statement st = null;
       Pessoa p = new Pessoa();  
        try{          
                conn = DataBaseLocator.getInsLocator().getConnection();
                st = conn.createStatement();
                st.executeQuery("Select * from Pessoa p where p.nome like '%"+nome+"%'");
                ResultSet rs = st.getResultSet();            
                 p.setId(rs.getInt("id"));
                 p.setNome(rs.getString("nome"));
                 p.setEmail(rs.getString("email"));
                 p.setEndereco(rs.getString("endereco"));
                 p.setCpf(rs.getString("cpf"));
                 p.setRg(rs.getString("rg"));
                 p.setTelefone(rs.getString("telefone"));
                 return p;
            } catch (Exception e) {
               e.printStackTrace();
               return null;
            }finally{
                closeResources(conn, st);
            }
    }
}
